package com.lilingguo.anime.utils;

import com.lilingguo.anime.domain.FolderPo;
import com.lilingguo.anime.service.FolderService;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 文件夹工具类
 *
 * @Author: GuoZi
 * @Date: 2020/11/03 16:37
 */
public class FolderUtils {

    private static String BASE_PATH;
    private static final String SUB_STRING = File.separator;

    private static FolderService SERVICE;

    private FolderUtils() {
    }

    static {
        init();
    }

    public static String getBasePath() {
        return BASE_PATH;
    }

    public static String getSubString() {
        return SUB_STRING;
    }

    private static void init() {
        InputStream is = null;
        try {
            // 获取配置文件参数
            Properties prop = new Properties();
            is = FolderUtils.class.getClassLoader().getResourceAsStream("folderConfig.properties");
            // GBK编码转换
            assert is != null;
            prop.load(new InputStreamReader(is, StandardCharsets.UTF_8));
            String os = System.getProperty("os.name");
            if (os.toLowerCase().startsWith("win")) {
                // Windows
                BASE_PATH = prop.getProperty("basePath.window");
            } else {
                // Linux
                BASE_PATH = prop.getProperty("basePath.linux");
            }
            System.out.println("BASE_PATH = " + BASE_PATH);
            System.out.println("SUB_STRING = " + SUB_STRING);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 将目录数据存入数据库中
     *
     * @return 执行结果
     */
    public static boolean load(FolderService service) {
        SERVICE = service;
        System.out.println("load start...");
        long start = System.currentTimeMillis();
        boolean result = save2DB();
        long end = System.currentTimeMillis();
        System.out.println("load over...");
        System.out.println("runtime:" + (end - start) + "ms");
        return result;
    }

    private static boolean save2DB() {
        File root = new File(BASE_PATH);
        if (!root.isDirectory()) {
            return false;
        }
        File[] listFiles = root.listFiles();
        if (listFiles == null) {
            return false;
        }
        for (File file : listFiles) {
            if (!save2DB(file)) {
                return false;
            }
        }
        return true;
    }

    private static boolean save2DB(File directory) {
        return save2DB(directory, null);
    }

    private static boolean save2DB(File directory, Integer parentId) {
        if (!directory.isDirectory()) {
            // not a directory
            return false;
        }
        File[] listFiles = directory.listFiles();
        if (listFiles == null) {
            // can't get subdirectory
            return false;
        }
        // count image number
        int size = 0;
        for (File file : listFiles) {
            // exclude thumbnail
            if (isImage(file) && !"_thumbnail.jpg".equals(file.getName())) {
                size++;
            }
        }
        FolderPo folder = new FolderPo();
        folder.setName(directory.getName());
        folder.setSize(size);

        Integer currentId;
        if (parentId == null) {
            currentId = SERVICE.saveRootFolder(folder);
        } else {
            currentId = SERVICE.saveFolder(folder, parentId);
        }
        if (currentId == null) {
            // save exception
            System.out.println("directory = " + directory);
            System.out.println("folder = " + folder);
            return false;
        }

        // save subdirectory
        for (File file : listFiles) {
            if (file.isDirectory()) {
                if (!save2DB(file, currentId)) {
                    return false;
                }
            }
        }
        return true;
    }

    public static String getThumbnailPath(String relativePath) {
        String path = BASE_PATH + relativePath + SUB_STRING + "_thumbnail.jpg";
        File file = new File(path);
        if (file.isFile()) {
            return path;
        }
        return null;
    }

    public static List<String> getImagesPath(String relativePath) {
        File file = new File(getRealPath(relativePath));
        if (!file.isDirectory()) {
            return null;
        }
        File[] listFiles = file.listFiles();
        if (listFiles == null || listFiles.length < 1) {
            return null;
        }
        List<String> imgList = new ArrayList<String>();
        for (File img : listFiles) {
            if (isImage(img)) {
                imgList.add(img.getAbsolutePath());
            }
        }
        if (imgList.isEmpty()) {
            return null;
        }
        Collections.sort(imgList);
        return imgList;
    }

    public static String getRealPath(String relativePath) {
        return BASE_PATH + SUB_STRING + relativePath;
    }

    /**
     * 判断文件是否为图片文件
     *
     * @param file 待判断文件
     * @return 判断结果
     */
    private static boolean isImage(File file) {
        if (!file.isFile()) {
            return false;
        }
        try {
            new SimpleImageInfo(file);
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    public static String getImagePath(String relativePath, int page) {
        return BASE_PATH + relativePath + SUB_STRING + "ghs_" + page + ".jpg";
    }
}
